package br.com.locadoracom.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.com.locadoracom.model.Titular;

public class TitularDao extends Dao<Titular>{
	EntityManagerFactory  emf = Persistence.createEntityManagerFactory("Locadora");
	EntityManager em = emf.createEntityManager();
	
	@Override
	public void create(Titular titular) {
		em.getTransaction().begin();
		em.persist(titular);
		em.getTransaction().commit();
	}

	@Override
	public Titular merge(Titular titular) {
		Titular temp;
		em.getTransaction().begin();
		temp = em.merge(titular);
		em.getTransaction().commit();
		return temp;
	}

	@Override
	public void remove(Titular titular) {
		em.getTransaction().begin();
		em.remove(titular);
		em.getTransaction().commit();
	}
	
	public Titular findById(Integer Id){
		return em.find(Titular.class, Id);
	}
	
	@SuppressWarnings("unchecked")
	public List<Titular> findByAll() throws Exception{
		String strQuery="select t from Titular t";
        Query rsQuery = em.createQuery(strQuery);
		return  rsQuery.getResultList();
	}
	
	public Titular findByCPF(String cpf){ 
		Query query = em.createQuery("select t from Titular t where t.cpf=:cpf");
		query.setParameter("cpf", cpf);
		if (query.getResultList().size() == 0)
			return null;
		return (Titular) query.getSingleResult();
	}
}